import { schemaTools } from "@gd-accbuild-core/config/utils";
import { globalConfig } from "@gd-accbuild-core/config/index";
/**
 * @description modelValue 的change事件监听器
 * - 若有一个metaItem中 监听器返回false 则中断setter执行
 * - 格式: metaEventListeners=[{metaKey:"",eventName:"_modelValueChange",immediate:true,func:(objConfig)=>{}}]
 */
export const genSetterListener = ({ metaItemList, metaItem, props, vm, executor = "setter" }) => {
  if (!Array.isArray(metaItemList)) {
    return async ({ val }) => true;
  }
  const allFuncs = metaItemList.map((brotherMetaItem) => {
    if (brotherMetaItem.hasOwnProperty("metaEventListeners") && brotherMetaItem.key !== metaItem.key) {
      const matchedListener = brotherMetaItem.metaEventListeners.find(
        (el) => el.metaKey === metaItem.key && el.eventName === "_modelValueChange"
      );
      const isAllowExecFunc = (matchedListener) => {
        return (
          executor === "setter" ||
          (executor === "getter" && (!matchedListener.hasOwnProperty("immediate") || matchedListener.immediate))
        );
      };
      if (matchedListener && isAllowExecFunc(matchedListener)) {
        //console.log("值监听器", matchedListener);
        return ({ val }) =>
          schemaTools.getDynmicAttr({
            val,
            valFunc: matchedListener.func,
            configObj: {
              rowIdx: props["rowIdx"],
              colIdx: props["colIdx"],
              metaKey: brotherMetaItem.key,
              metaItem: brotherMetaItem,
              metaItemList: props["metaItemList"],
              rowData: props["rowData"],
              formData: props["formData"],
              tableBodyData: props["tableBodyData"],
              sourceMetaEventConfigObj: {
                value: val,
                metaKey: metaItem.key,
                metaItem,
              },
              vm,
              globalConfig,
            },
          });
      } else {
        return ({ val }) => {};
      }
    } else {
      return ({ val }) => {};
    }
  });
  return async ({ val }) => {
    try {
      const promiseArr = [];
      allFuncs.forEach((el) => {
        promiseArr.push(el({ val }));
      });
      const allRes = await Promise.all(promiseArr);
      const isStopSetter = allRes.some((r) => typeof r === "boolean" && !r);
      return !isStopSetter;
    } catch (error) {
      console.log(error, "报错");
      return true;
    }
  };
};
